package com.sanpu.kxe.business.card.presenter;

import android.text.TextUtils;
import android.util.Log;

import com.sanpu.kxe.business.card.bean.BankInfoInput;
import com.sanpu.kxe.business.card.contract.VerificationContract;
import com.sanpu.kxe.business.card.model.CardModel;
import com.sanpu.kxe.business.card.view.AddBankSecondActivity;
import com.sanpu.kxe.business.card.view.AddBankSetupActivity;
import com.sanpu.kxe.business.card.view.VerificationActivity;
import com.sanpu.kxe.business.login.provider.ILoginProvider;
import com.sanpu.kxe.business.main.bean.UserCenterOutput;
import com.sanpu.kxe.common.cache.CacheManage;
import com.sanpu.kxe.common.cache.CacheModel;
import com.sanpu.kxe.common.interfaces.CommonConfig;
import com.sanpu.kxe.jump.eventbus.RefreshBankEvent;
import com.sanpu.kxe.utils.AppContextUtil;
import com.sanpu.kxe.utils.PublicProviderUtil;
import com.sanpu.kxe.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Description：校验验证码
 * Created by 薛勇军 on 2018/7/24.
 */

public class VerificationPresenter implements VerificationContract.Presenter {

    private VerificationContract.View mView;

    private CompositeSubscription mSubscription;

    private BankInfoInput mInfoInput = null;

    public VerificationPresenter(VerificationContract.View mView) {
        this.mView = mView;
        mSubscription = new CompositeSubscription();
    }

    @Override
    public void initViewData(BankInfoInput infoInput) {
        mInfoInput = infoInput;
        UserCenterOutput centerOutput = CacheManage.getInstance().getCache(CacheModel.USER_CENTER_KEY);
        if (centerOutput != null && mInfoInput != null) {
            mInfoInput.setAccountName(centerOutput.getUserName());
        }

    }

    @Override
    public void onCommit(String smsCode) {
        if (TextUtils.isEmpty(smsCode)) {
            ToastUtil.showTextViewPrompt("请填写验证码");
            return;
        }
        mInfoInput.setSmsCode(smsCode);
        mView.showLoadingDialog(false);
        Subscription subscription = CardModel.getInstance().insertUrmBank(mInfoInput)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(String s) {
                        ToastUtil.showTextViewPrompt("添加银行卡成功！");
                        EventBus.getDefault().post(new RefreshBankEvent());
//                        CardOpenProvider.getInstance().openAddBankResultActivity(mView.getContext());
                        AppContextUtil.finishActivity(VerificationActivity.class.getName(),
                                AddBankSecondActivity.class.getName(), AddBankSetupActivity.class.getName());
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public void sendCode() {
        if (mInfoInput == null || TextUtils.isEmpty(mInfoInput.getRsdTel())) {
            ToastUtil.showTextViewPrompt("手机号码不能为空");
            return;
        }
        Observable.interval(0, 1, TimeUnit.SECONDS)//设置0延迟，每隔一秒发送一条数据
                .take(CommonConfig.SMS_SEC + 1) //设置循环次
                .map(new Func1<Long, Long>() {
                    @Override
                    public Long call(Long aLong) {
                        return CommonConfig.SMS_SEC - aLong;
                    }
                })
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        sendSms();
                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onCompleted() {
                        mView.changeByStatus(false);
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(Long aLong) { //接受到一条就是会操作一次UI
                        Log.e("Register", "onNext: " + aLong);
                        mView.byoyomi(aLong);
                    }
                });
    }

    /**
     * 发送验证码
     */
    private void sendSms() {
        ILoginProvider provider = PublicProviderUtil.getProvider(ILoginProvider.class);
        if (provider != null) {
            mView.changeByStatus(true);
            Subscription subscription = provider.sendSms(mInfoInput.getRsdTel(), CommonConfig.SMSTYPE_ADDBANK)
                    .subscribeOn(Schedulers.io())
                    .unsubscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<String>() {
                        @Override
                        public void onCompleted() {

                        }

                        @Override
                        public void onError(Throwable e) {
                            mView.dismissLoadingDialog();
                            mView.showErrorText(e);
                        }

                        @Override
                        public void onNext(String s) {
                            ToastUtil.showTextViewPromptShort("验证码发送成功！");
                        }
                    });
            mSubscription.add(subscription);
        }
    }

    @Override
    public void onDestroyPresenter() {
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
        if (mView != null) {
            mView = null;
        }
    }
}
